package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Result;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author gakki
 * @create 2022/5/3 21:51
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成随机验证，并通过手机短信发送
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMessage(@RequestBody User user) {
        //获取手机号
        String phone = user.getPhone();
        //创建redistemplate,valueOperations
        ValueOperations valueOperations = redisTemplate.opsForValue();

        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("短信验证服务，code：{}", code);

            //验证码存值,存活时间为120s
            valueOperations.set(phone, code, 120, TimeUnit.SECONDS);
            return Result.success("短信发送成功！");
        }

        return Result.error("短信发送失败！");
    }

    /**
     * 移动端登录
     * @param map
     * @return
     */
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map,HttpSession session) {
        log.info(map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //创建redisTemplate,valueOperations
        ValueOperations valueOperations = redisTemplate.opsForValue();

        //从redis中取出验证码
        String redisCode = (String) valueOperations.get(phone);

        //从Session中获取保存的验证码
        //String sessionCode = (String) session.getAttribute(phone);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        //if (StringUtils.isNotEmpty(sessionCode) && sessionCode.equals(code)) {
        if (StringUtils.isNotEmpty(redisCode) && redisCode.equals(code)) {
            //如果能够比对成功，说明登录成功
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(lambdaQueryWrapper);

            //判断当前手机号对应的用户是否为新用户，如果是新用户就自动完成注册
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //登录成功，删除redis数据
            redisTemplate.delete(phone);
            //session保存信息
            session.setAttribute("user", user.getId());
            return Result.success(user);
        }
        return Result.error("登录失败！");
    }

    /**
     * 移动端退出登录
     * @param session
     * @return
     */
    @PostMapping("/loginout")
    public Result<String> loginout(HttpSession session) {
        log.info("移动端退出登录！");
        Long userId = (Long) session.getAttribute("user");
        User user = userService.getById(userId);
        session.removeAttribute(user.getPhone());
        session.removeAttribute("user");
        return Result.success("用户退出成功！");
    }
}
